Skip to content

fix: validate ActivityFeed API response schema#507

Merged
mehul-m-prajapati merged 1 commit into
GitMetricsLab:mainfrom
Tanayajadhav1:fix/activityfeed-response-validation-505
May 29, 2026
Merged

fix: validate ActivityFeed API response schema#507
mehul-m-prajapati merged 1 commit into
GitMetricsLab:mainfrom
Tanayajadhav1:fix/activityfeed-response-validation-505

Conversation

@Tanayajadhav1
Copy link
Copy Markdown
Contributor

@Tanayajadhav1 Tanayajadhav1 commented May 25, 2026

Related Issue

Description

Implemented runtime validation and improved error handling for the ActivityFeed component to prevent unsafe API responses from causing runtime failures.

Changes made:

  • Added HTTP response validation using res.ok
  • Added custom ActivityFeedError class for structured error handling
  • Implemented runtime type guard validation for EventType[]
  • Added validation for optional repo.name field
  • Added graceful handling for invalid API responses and GitHub rate-limit responses
  • Prevented invalid API data from being assigned to state
  • Improved fallback error UI

This improves runtime safety, API reliability, and overall stability of the ActivityFeed component.

How Has This Been Tested?

  • Verified TypeScript compilation passes successfully
  • Manually reviewed different API failure scenarios and validation paths

Screenshots (if applicable)

N/A

Type of Change

  • Bug fix
  • New feature
  • Code style update
  • Breaking change
  • Documentation update

###Suggested Labels :
gssoc'26,gssoc:approved , type:fix , level:intermediate , quality:clean

Summary by CodeRabbit

  • Bug Fixes
    • Activity Feed now displays specific error messages when GitHub API rate limits are exceeded
    • Added a "No activity found" state for clearer feedback when no data is available
    • Improved error detection and user-facing messages for failed API requests

Review Change Stack

Copilot AI review requested due to automatic review settings May 25, 2026 11:42
@netlify
Copy link
Copy Markdown

netlify Bot commented May 25, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit 4a548d0
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a1435a0aaeca500085c5e2d
😎 Deploy Preview https://deploy-preview-507--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 25, 2026

📝 Walkthrough

Walkthrough

The PR adds comprehensive error handling and runtime response validation to the ActivityFeed component. It introduces a FetchError type, ActivityFeedError exception class, and isEventTypeArray type guard for validating the GitHub API response. The fetchEvents routine now checks HTTP success, detects rate-limit errors (HTTP 403), and throws structured exceptions. The UI conditionally renders error panels with specific messaging for rate limits and 404s before displaying activity.

Changes

Activity Feed Error Handling

Layer / File(s) Summary
Error types and response validation contracts
src/components/ActivityFeed.tsx
FetchError type, ActivityFeedError custom Error class with statusCode, and isEventTypeArray type guard validate the GitHub /events response shape at runtime; component adds error state to track fetch or validation failures.
Fetch logic with error handling
src/components/ActivityFeed.tsx
fetchEvents clears prior errors, validates res.ok, detects HTTP 403 rate-limit responses, throws ActivityFeedError with status code, validates successful responses using isEventTypeArray, catches errors to set state while clearing events, and ensures loading is disabled via finally.
Error UI rendering and fallback states
src/components/ActivityFeed.tsx
Conditional rendering replaces the static loading message: error panel appears when error exists (with rate-limit and 404-specific messaging), "No activity found" shows only when not loading with zero events, and the activity list renders otherwise.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • GitMetricsLab/github_tracker#276: Earlier ActivityFeed implementation that this PR builds upon with added runtime response validation and rate-limit detection.

Suggested labels

level:intermediate, quality:clean

Poem

🐰 A little rabbit hops with glee,
"No more crashes when data's free!
Validation guards each API call,
Rate limits caught—we've fixed it all!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: validating ActivityFeed API response schema, which is the core objective of this PR.
Description check ✅ Passed The description follows the template with all required sections completed: Related Issue, Description with detailed changes, How Has This Been Tested, Screenshots, and Type of Change.
Linked Issues check ✅ Passed All coding requirements from issue #505 are met: HTTP response validation (res.ok), custom error class, runtime type guard validation, optional field handling, rate-limit detection, and fallback error UI.
Out of Scope Changes check ✅ Passed All changes in ActivityFeed.tsx are directly related to schema validation and error handling objectives from #505; no out-of-scope modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Improves runtime safety of the ActivityFeed React component by validating GitHub API responses at runtime and surfacing structured, user-friendly errors instead of letting unexpected responses crash rendering.

Changes:

  • Added a runtime type-guard (isEventTypeArray) to validate the /users/:username/events payload before setting component state.
  • Added structured error handling via ActivityFeedError + FetchError state, including special-casing for rate-limit and 404 scenarios.
  • Updated the UI to show clearer loading, empty-state, and error-state messaging.
Comments suppressed due to low confidence (1)

src/components/ActivityFeed.tsx:166

  • The rate-limit helper text says "The limit resets in 1 hour", but GitHub rate limits reset at a specific time (available via X-RateLimit-Reset) and may be sooner/later than 1 hour depending on when the limit was hit. Consider either computing the reset time from the header or using a non-specific message to avoid misleading users.
            <p className="text-xs text-red-600 dark:text-red-400 mt-2">
              You've hit GitHub's API rate limit. The limit resets in 1 hour.
            </p>

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/components/ActivityFeed.tsx
Comment thread src/components/ActivityFeed.tsx
Comment thread src/components/ActivityFeed.tsx
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/components/ActivityFeed.tsx (1)

77-141: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Prevent stale/overlapping fetches from overwriting newer state.

Line 77-141 can commit outdated responses when requests overlap (interval tick, slow network, or username change), which can show the wrong feed/error state.

Suggested fix (ignore stale responses + cleanup-safe updates)
 useEffect(() => {
+  let isActive = true;
+  let latestRequestId = 0;
+
   const fetchEvents = async () => {
+    const requestId = ++latestRequestId;
     try {
       setLoading(true);
       setError(null);

       const res = await fetch(
         `https://api.github.com/users/${username}/events`
       );

@@
-      setEvents(data);
+      if (!isActive || requestId !== latestRequestId) return;
+      setEvents(data);
     } catch (err) {
+      if (!isActive || requestId !== latestRequestId) return;
       const fetchError: FetchError = {
         message: "Failed to fetch activity. Please try again.",
         isRateLimited: false,
       };
@@
       setError(fetchError);
       console.error("ActivityFeed fetch error:", fetchError);
       setEvents([]);
     } finally {
-      setLoading(false);
+      if (isActive && requestId === latestRequestId) {
+        setLoading(false);
+      }
     }
   };

   fetchEvents();

   const interval = setInterval(fetchEvents, 30000);
-  return () => clearInterval(interval);
+  return () => {
+    isActive = false;
+    clearInterval(interval);
+  };
 }, [username]);

Also applies to: 146-148

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/ActivityFeed.tsx` around lines 77 - 141, The fetchEvents
useEffect can let slower responses overwrite newer state; fix it by making
fetchEvents cancellation-safe: create an AbortController (or increment a local
requestId/flag) inside the useEffect, pass its signal to fetch, and in the
finally/then blocks only call setEvents, setError, and setLoading if the request
wasn't aborted and the requestId matches the latest; also abort the controller
(or flip the flag) in the effect cleanup so overlapping interval ticks or
username changes can't commit stale responses; this touches useEffect,
fetchEvents, ActivityFeedError handling, and the setEvents/setError/setLoading
calls.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/components/ActivityFeed.tsx`:
- Around line 89-103: The code currently treats any 403 as a rate-limit by using
isRateLimited = res.status === 403; change this to detect rate limiting from
response headers and message: inspect res.headers for x-ratelimit-remaining,
x-ratelimit-reset, Retry-After (and treat remaining === "0" or presence of
Retry-After as rate-limited), and also check errorData.message or errorData for
rate-limit phrases like "rate limit" or "secondary rate limit"; then set
isRateLimited based on those signals and use that boolean when constructing the
ActivityFeedError (referencing isRateLimited, res.headers, and
errorData.message) so only true rate-limit responses produce the rate-limit
message.

---

Outside diff comments:
In `@src/components/ActivityFeed.tsx`:
- Around line 77-141: The fetchEvents useEffect can let slower responses
overwrite newer state; fix it by making fetchEvents cancellation-safe: create an
AbortController (or increment a local requestId/flag) inside the useEffect, pass
its signal to fetch, and in the finally/then blocks only call setEvents,
setError, and setLoading if the request wasn't aborted and the requestId matches
the latest; also abort the controller (or flip the flag) in the effect cleanup
so overlapping interval ticks or username changes can't commit stale responses;
this touches useEffect, fetchEvents, ActivityFeedError handling, and the
setEvents/setError/setLoading calls.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: df365c70-9185-453d-8499-6878fbb3a899

📥 Commits

Reviewing files that changed from the base of the PR and between 6c6bc3e and 4a548d0.

📒 Files selected for processing (1)
  • src/components/ActivityFeed.tsx

Comment thread src/components/ActivityFeed.tsx
@mehul-m-prajapati mehul-m-prajapati merged commit 5d717ca into GitMetricsLab:main May 29, 2026
10 of 11 checks passed
@github-actions
Copy link
Copy Markdown

🎉🎉 Thank you for your contribution! Your PR #507 has been merged! 🎉🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug Report: ActivityFeed Response Schema Not Validated

3 participants